#!/bin/bash

# 启动测试脚本
set -e

echo "=== 智能视频内容结构重构平台 - 启动测试 ==="

# 检查Docker是否运行
if ! docker info > /dev/null 2>&1; then
    echo "错误: Docker未运行，请先启动Docker"
    exit 1
fi

echo "1. 检查环境配置..."

# 检查.env文件是否存在
if [ ! -f .env ]; then
    echo "创建.env文件..."
    cp .env.example .env
fi

if [ ! -f backend/.env ]; then
    echo "创建backend/.env文件..."
    cp backend/.env.example backend/.env
fi

if [ ! -f frontend/.env ]; then
    echo "创建frontend/.env文件..."
    cp frontend/.env.example frontend/.env
fi

echo "2. 停止现有容器（如果有）..."
docker-compose down

echo "3. 构建并启动服务..."
docker-compose up -d --build

echo "4. 等待服务启动..."
sleep 10

echo "5. 初始化数据库..."
chmod +x scripts/init-db.sh
./scripts/init-db.sh

echo "6. 检查服务健康状态..."

# 检查后端API
echo "检查后端API..."
for i in {1..30}; do
    if curl -s http://localhost:8000/api/v1/health > /dev/null; then
        echo "✓ 后端API健康检查通过"
        break
    else
        if [ $i -eq 30 ]; then
            echo "✗ 后端API健康检查失败"
            exit 1
        fi
        echo "等待后端API启动... ($i/30)"
        sleep 2
    fi
done

# 检查前端
echo "检查前端服务..."
for i in {1..30}; do
    if curl -s http://localhost:3000 > /dev/null; then
        echo "✓ 前端服务健康检查通过"
        break
    else
        if [ $i -eq 30 ]; then
            echo "✗ 前端服务健康检查失败"
            exit 1
        fi
        echo "等待前端服务启动... ($i/30)"
        sleep 2
    fi
done

# 检查数据库
echo "检查数据库连接..."
if docker-compose exec -T postgres pg_isready -U videoadmin; then
    echo "✓ 数据库连接正常"
else
    echo "✗ 数据库连接失败"
    exit 1
fi

# 检查Redis
echo "检查Redis连接..."
if docker-compose exec -T redis redis-cli -a redispass ping | grep -q PONG; then
    echo "✓ Redis连接正常"
else
    echo "✗ Redis连接失败"
    exit 1
fi

# 检查MinIO
echo "检查MinIO服务..."
if curl -s http://localhost:9000/minio/health/live > /dev/null; then
    echo "✓ MinIO服务正常"
else
    echo "✗ MinIO服务异常"
    exit 1
fi

echo ""
echo "=== 所有服务启动成功！ ==="
echo ""
echo "访问地址："
echo "  前端应用:    http://localhost:3000"
echo "  后端API:     http://localhost:8000"
echo "  API文档:     http://localhost:8000/docs"
echo "  MinIO控制台: http://localhost:9001 (minioadmin/minioadmin)"
echo "  Flower监控:  http://localhost:5555"
echo ""
echo "查看日志: docker-compose logs -f [service_name]"
echo "停止服务: docker-compose down"
echo ""

# 测试API端点
echo "7. 测试API端点..."

echo "测试健康检查..."
curl -s http://localhost:8000/api/v1/health | python3 -m json.tool

echo ""
echo "测试平台模板API..."
curl -s http://localhost:8000/api/v1/videos/templates | python3 -m json.tool

echo ""
echo "=== 启动测试完成！ ==="
echo "现在可以访问 http://localhost:3000 开始使用平台"